package persistence

import (
	"context"
	"errors"
	"example.com/m/v2/internal/domain/account_aggregate/entity"
	"example.com/m/v2/internal/domain/account_aggregate/repository"
	"gorm.io/gorm"
	"log"
)

type mainAccountRepository struct {
	db *gorm.DB
}

func (repo *mainAccountRepository) Migrate() error {
	err := repo.db.AutoMigrate(&MainAccountPo{})
	if err != nil {
		return err
	}
	return nil
}

func (repo *mainAccountRepository) Save(context context.Context, entity *entity.MainAccountEntity) (*entity.MainAccountEntity, error) {
	if entity == nil {
		return nil, errors.New("not allow to save an null entity")
	}
	po := MainAccountPo{}
	err := po.FromEntity(entity)
	if err != nil {
		return nil, err
	}
	repo.db.Create(&po)
	return po.ToEntity()
}

func (repo *mainAccountRepository) FindById(context context.Context, id uint) (*entity.MainAccountEntity, error) {
	var po MainAccountPo
	result := repo.db.First(&po, id)

	//// 记录不存在
	//if result.Error != nil && errors.Is(result.Error, gorm.ErrRecordNotFound) {
	//	return nil, result.Error
	//}
	if result.Error != nil {
		return nil, result.Error
	}

	do, err := po.ToEntity()
	if err != nil {
		return nil, err
	}
	return do, nil
}

func NewMainAccountRepository(db *gorm.DB) repository.MainAccountRepository {
	log.Printf("main account repository constructed")
	return &mainAccountRepository{db}
}
